package yaowen.com.baseadapter_gallery;

import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.TextView;

public class Main extends AppCompatActivity {
    private Gallery gallery;
    private ImageView imageView;
    private TextView textView;
    //图片数组
    private int[] pics={
            R.drawable.pic1,R.drawable.pic2,
            R.drawable.pic3,R.drawable.pic4,
            R.drawable.pic5,R.drawable.pic6
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        imageView= (ImageView) findViewById(R.id.imageView);
        gallery= (Gallery) findViewById(R.id.gallery);
        textView= (TextView) findViewById(R.id.textView);
        MyAdapter adapter=new MyAdapter(this);
        gallery.setAdapter(adapter);
        gallery.setOnItemClickListener(new Gallery.OnItemClickListener(){

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                int i=position+1;
                imageView.setImageResource(pics[position]);
                textView.setText("这是第"+i+"张图片");
            }
        });
    }
    //内部类实现BaseAdapter
    class MyAdapter extends BaseAdapter{

        //用来接收传递过来的Context上下文对象
        private Context context;
        //构造函数
        public MyAdapter(Context context)
        {
            this.context = context;
        }


        @Override
        public int getCount() {
            //返回图片数组大小
            return pics.length;
        }

        @Override
        public Object getItem(int position) {
            //根据选中项返回索引位置
            return position;
        }

        @Override
        public long getItemId(int position) {
            //根据选中项id返回索引位置
            return position;
        }
        //未优化的getView，这部分可以使用recycle()释放内存、或者BitmapFacotry.Options缩小，或者软引用，或者控制图片资源大小等等很多方法
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView img=new ImageView(context);
            img.setAdjustViewBounds(true);
            img.setImageResource(pics[position]);
            img.setScaleType(ImageView.ScaleType.FIT_XY);
            img.setLayoutParams(new Gallery.LayoutParams(120,120));

            return img;
        }
    }

}
